/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.os.dao.zakharov.oracledao;

import edu.os.dao.zakharov.interfacedao.RegistrationDAO;
import edu.os.dao.zakharov.oracle.Registration;
import java.math.BigDecimal;
import java.rmi.RemoteException;
import javax.annotation.Resource;
import javax.ejb.*;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public class OracleRegistrationDAO implements RegistrationDAO {

    @Resource
    private SessionContext sessionContext;
    
    @PersistenceContext(unitName = "OnlineStore-ejbPU")
    private EntityManager em;

    @Override
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public BigDecimal addRegistration(String surname, String name, String patronymic,
            String email, String country, String city) throws RemoteException {

        em.flush();
        Query query = null;

        try {
            query = em.createNativeQuery("select sq_REGISTRATION.nextval from dual");

            Registration registration = new Registration((BigDecimal) query.getSingleResult());
            registration.setSurname(surname);
            registration.setName(name);
            registration.setPatronymic(patronymic);
            registration.setEmail(email);
            registration.setCountry(country);
            registration.setCity(city);

            em.persist(registration);

            return (BigDecimal) query.getSingleResult();

        } catch (Exception e) {
            e.printStackTrace();
            sessionContext.setRollbackOnly();
            return new BigDecimal(0);
        }
    }
}
